import localstorage from 'localStorage';
import { request, requestWithAuth } from '../utils/request';
import { uploadtocos } from '../utils/uploadtocos';
import { Toast } from 'antd-mobile';
import cons from '../constan';
import { routerRedux } from 'dva/router';
import config from '../config';
function randomWord(l) {
    var  x="0123456789qwertyuioplkjhgfdsazxcvbnm";
    var  tmp="";
    var  timestamp = new Date().getTime();
    for(var i=0;i<l;i++)  {
        tmp += x.charAt(Math.ceil(Math.random()*100000000)%x.length);
    }
    return tmp+timestamp;
}
export default {
    namespace: 'user',
    state: {
        account: '尚未登陆',
        phone: '',
        photo: 'https://image.flaticon.com/icons/svg/145/145867.svg',
        valid_name: '',
        valid: '',
        login_state: cons.UnLogin,
    },
    subscriptions: {
        setup({ dispatch, history }) {  // eslint-disable-line
            dispatch({ type: 'loginWithoutPwd' })
        },
    },

    effects: {
        *register ({payload}, {put}){
            let account = randomWord(6);
            let params = {account,...payload};
            //console.log(params);
            const res = yield request(config.requestUrl + "/api/v1/register", {
                method: 'post',
                body: JSON.stringify(params),
                headers: {
                    "Content-Type": "application/json",
                },
            })
            console.log(res)
            const { data: { code, data } } = res;
            console.log('code',code);
            console.log('data',data.isexist);
            if (code === 0) {
                if (data.isexist) yield Toast.fail('该帐号已被注册');
                else {
                    yield Toast.success('注册成功');
                    yield put(routerRedux.push('/login'));
                }
            }
            else{
                yield Toast.info('注册失败');
            }
        },
        *gotologin({ payload }, { put }) {
            console.log('gotologin');
            yield put(routerRedux.push('/login'));
        },
        //用于设置用户信息 
        *setinfo({ payload }, { put }) {
            const { nickname, photo } = payload;
            //前端直接上传图片到cos
            //图片文件流
            const photourl = photo.url
            //图片文件名
            const photoname = randomWord(3)
            //调用上传util
            const res = uploadtocos(photourl,photoname);

            const params = {
                nickname,
                'photo': photoname
            }
            const res2 = yield requestWithAuth(config.requestUrl + "/api/v1/setinfo", {
                method: 'post',
                body: JSON.stringify(params),
            })
            console.log(res2);
            if (res.data.serverStatus === 34) {
                yield Toast.success('信息修改成功');
                yield put({ type: 'loginWithoutPwd' });
            } else {
                yield Toast.fail('信息修改失败');
            }            
            yield put(routerRedux.push('/my/info'));
        },
        *login({ payload: { id, pwd } }, { put }) {
            console.log('login');
            const params = { mobile: id, password: pwd };
            const res = yield request(config.requestUrl + "/api/v1/login", {
                method: 'post',
                body: JSON.stringify(params),
                headers: {
                    "Content-Type": "application/json",
                },
            })
            console.log(res);
            const { data: { code, data } } = res;
            if (code === 0) {
                const myValue = { token: data.token };
                localstorage.setItem('auth', JSON.stringify(myValue));
                yield put({ type: 'loginSuccess', payload: { ...data } });
                yield Toast.success('登陆成功');
                yield put(routerRedux.push('/my'));

            } else {
                yield put({ type: 'loginFail' });
                Toast.fail('密码或用户名错误');
            }

        },
        *loginout({ payload }, { put }) {
            console.log('loginout effect');
            localstorage.removeItem('auth');
            yield put(routerRedux.push('/login'));
        },
        *loginWithoutPwd({ payload }, { put }) {
            if (localstorage.getItem('auth') == null) return;
            console.log('使用localstorage发送登陆请求', localstorage.getItem('auth'));
            const authstorage = JSON.parse(localstorage.getItem('auth'));
            if (typeof authstorage.token === 'undefined') return;
            const { token } = authstorage;
            const res = yield request("http://127.0.0.1:7001/api/v1/u/", {
                method: 'get',
                headers: {
                    "Content-Type": "application/json",
                    "authorization": "Bearer " + token
                },
            })
            console.log(res);
            const {data} = res;
            if (data.code === 0) 
                yield put({type:'loginSuccess' , payload:{...data.data}});

            /**
            let {data:{rolpic}} = yield request("http://127.0.0.1:7001/api/v1/home",{
                method: 'post',
                headers: {
                  "Content-Type": "application/json",
                },
            });
            */
        },
    },

    reducers: {
        loginSuccess(state, action) {
            let info = action.payload
            if(info.photo === null) info.photo = "https://image.flaticon.com/icons/svg/145/145867.svg"  
            return { ...state, login_state: cons.SuccessLogin, ...info }
        },
        loginFail(state){
            return {...state, login_state: cons.FailLogin}
        },
        LoginOut(state){
            return {...state, login_state: cons.UnLogin}
        }
    },

};
